package com.dream.provider;

import cn.hutool.core.util.ObjectUtil;
import com.dream.entity.JwtUser;
import com.dream.entity.OauthAuthenticationToken;
import com.dream.service.UserDetailsServiceImpl;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;

/**
 * 单点登录的Provider,作用同默认的DaoAuthenticationProvider对象，
 */
public class OauthAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    /**
     * 验证登录信息
     * @param authentication the authentication request object.
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取对象
        String username = authentication.getPrincipal().toString();
        if (ObjectUtil.isEmpty(username)){
            throw new UsernameNotFoundException("用户名为空");
        }
        JwtUser jwtUser = (JwtUser) userDetailsService.loadUserByUsername(username);

        return new OauthAuthenticationToken(jwtUser,null, jwtUser.getAuthorities());
    }

    /**
     * 只有authentication是OauthAuthenticationToken对象才会走此类的authenticate方法
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return OauthAuthenticationToken.class.equals(authentication);
    }
}
